package com.chenfan.ccp.generator.utils;

import com.chenfan.ccp.core.utils.DateUtil;
import com.chenfan.ccp.core.utils.StringUtil;
import com.chenfan.ccp.generator.entity.ColumnEntity;
import com.chenfan.ccp.generator.entity.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器   工具类
 */
public class GenUtils {

    /**
     * 生成代码
     */
    public static void generatorCode(Map<String, String> table,
                                     List<Map<String, String>> columns, ZipOutputStream zip) {
        //配置信息
        Configuration config = getConfig();
        String company_name = config.getString("company_name");
        String app_name = config.getString("app_name");
        String module_name = config.getString("module_name");
        String app_pck_name = "com."+company_name+"."+app_name;
        boolean hasBigDecimal = false;
        //表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName" ));
        tableEntity.setComments(table.get("tableComment" ));
        //表名转换成Java类名
        String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix" ));
        tableEntity.setClassName(className);
        tableEntity.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnEntity> columsList = new ArrayList<ColumnEntity>();
        for(Map<String, String> column : columns){
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("columnName" ));
            columnEntity.setDataType(column.get("dataType" ));
            columnEntity.setComments(column.get("columnComment" ));
            columnEntity.setExtra(column.get("extra" ));

            //列名转换成Java属性名
            String attrName = camelize(columnEntity.getColumnName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), "unknowType" );
            columnEntity.setAttrType(attrType);
            if (!hasBigDecimal && attrType.equals("BigDecimal" )) {
                hasBigDecimal = true;
            }
            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey" )) && tableEntity.getPk() == null) {
                tableEntity.setPk(columnEntity);
            }

            columsList.add(columnEntity);
        }
        tableEntity.setColumns(columsList);

        //没主键，则第一个字段为主键
        if (tableEntity.getPk() == null) {
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" );
        Velocity.init(prop);
        //封装模板数据
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tableName", tableEntity.getTableName());
        map.put("comments", tableEntity.getComments());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getClassName());
        map.put("classname", tableEntity.getClassname());
        map.put("columns", tableEntity.getColumns());
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("company_name", company_name);
        map.put("app_name", app_name);
        map.put("module_name", module_name);
        map.put("author", config.getString("author" ));
        map.put("email", config.getString("email" ));
        map.put("datetime", DateUtil.parse2Str(new Date(), DateUtil.DATE_TIME_ALL_FORMAT));
        VelocityContext context = new VelocityContext(map);


        //1、生成service层代码------------java代码
        String serviceModule = "service";
        deal(context,zip,tableEntity, "template/module/api/Entity.java.vm",serviceModule+".java."+app_pck_name + "."+serviceModule+".bean.entity."+ className + ".java");
        deal(context,zip,tableEntity, "template/module/api/EntityP.java.vm",serviceModule+".java."+app_pck_name + "."+serviceModule+".bean.param."+ className + "P.java");
        deal(context,zip,tableEntity, "template/module/api/Dao.java.vm",serviceModule+".java."+app_pck_name + "."+serviceModule+".dao."+ className + "Dao.java");
        deal(context,zip,tableEntity, "template/module/api/Service.java.vm",serviceModule+".java."+app_pck_name + "."+serviceModule+".service.itf."+ className + "Service.java");
        deal(context,zip,tableEntity, "template/module/api/ServiceImpl.java.vm",serviceModule+".java."+app_pck_name + "."+serviceModule+".service."+ className + "ServiceImpl.java");
        //1、生成service层代码------------xml代码
        deal(context,zip,tableEntity, "template/module/api/Dao.xml.vm",serviceModule+".resources.mapper."+ module_name +"."+ className + "Dao.xml");

        //2、生成模块代码
        deal(context,zip,tableEntity, "template/module/api/Controller.java.vm",module_name+".java."+app_pck_name + "."+module_name+".api.controller."+ className + "Controller.java");

    }

    //将包路径转换为文件路径
    public static String dealPath(String file){
        return StringUtil.replaceLast(file.replace(".",File.separator),File.separator,".");
    }


    public static void deal(VelocityContext context, ZipOutputStream zip,TableEntity tableEntity, String templateFile,String desFile){
        //渲染模板
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate(templateFile, "UTF-8" );
        tpl.merge(context, sw);
        try {
            //添加到zip
            zip.putNextEntry(new ZipEntry(dealPath(desFile)));
            IOUtils.write(sw.toString(), zip, "UTF-8" );
            IOUtils.closeQuietly(sw);
            zip.closeEntry();
        } catch (IOException e) {
            throw new KKException("渲染模板失败，表名：" + tableEntity.getTableName(), e);
        }
    }


    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "" );
    }

    private static String camelize(String tabAttr){
        if(StringUtils.isEmpty(tabAttr))

            return tabAttr;

        Pattern pattern = Pattern.compile("(.*)_(\\w)(.*)");
        Matcher matcher = pattern.matcher(tabAttr);

        if(matcher.find()){
            return camelize(matcher.group(1) + matcher.group(2).toUpperCase() + matcher.group(3));
        }else{
            return tabAttr;
        }

    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replaceFirst(tablePrefix, "" );
        }
        return camelize(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties" );
        } catch (ConfigurationException e) {
            throw new KKException("获取配置文件失败，", e);
        }
    }


    /**
     * 生成代码
     */
    public static void generatorProject(ZipOutputStream zip) {
        //配置信息
        Configuration config = getConfig();


        String company_name = config.getString("company_name");
        String app_name = config.getString("app_name");
        String module_name = config.getString("module_name");
        String app_pck_name = "com."+company_name+"."+app_name;

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" );
        Velocity.init(prop);
        //封装模板数据
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("company_name", company_name);
        map.put("app_name", app_name);
        map.put("module_name", module_name);
        map.put("module_Name", StringUtils.capitalize(module_name));
        map.put("author", config.getString("author" ));
        map.put("email", config.getString("email" ));
        map.put("datetime", DateUtil.parse2Str(new Date(), DateUtil.DATE_TIME_ALL_FORMAT));
        VelocityContext context = new VelocityContext(map);

        String proj_dir = company_name+"-"+app_name;
        //生成总pom文件
        deal(context,zip,null, "template/proj/pom.xml.vm",proj_dir + ".pom.xml");

        //1、生成service层代码------------java代码
        String service_dir = app_name+"-service";
        deal(context,zip,null, "template/proj/service/pom.xml.vm",proj_dir+"."+service_dir + ".pom.xml");
        deal(context,zip,null, "template/proj/service/base/itf/BaseDao.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/base/itf/BaseDao.java");
        deal(context,zip,null, "template/proj/service/base/itf/BaseService.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/base/itf/BaseService.java");
        deal(context,zip,null, "template/proj/service/base/BaseServiceImpl.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/base/BaseServiceImpl.java");
        deal(context,zip,null, "template/proj/service/base/RedisService.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/base/RedisService.java");

        deal(context,zip,null, "template/proj/service/common/config/MybatisConfig.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/common/config/MybatisConfig.java");
        deal(context,zip,null, "template/proj/service/common/config/RedisConfig.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/common/config/RedisConfig.java");
        deal(context,zip,null, "template/proj/service/common/constants/BizCode.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/common/constants/BizCode.java");
        deal(context,zip,null, "template/proj/service/common/constants/KeyConstants.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/common/constants/KeyConstants.java");
        deal(context,zip,null, "template/proj/service/common/constants/RedisKey.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/common/constants/RedisKey.java");
        deal(context,zip,null, "template/proj/service/common/exception/ApiExceptionHandler.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/common/exception/ApiExceptionHandler.java");
        deal(context,zip,null, "template/proj/service/common/interceptor/GlobalFilter.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/common/exception/GlobalFilter.java");
        deal(context,zip,null, "template/proj/service/common/interceptor/MybatisInterceptor.java.vm",proj_dir + "."+service_dir+".src.main.java."+app_pck_name + ".service/common/exception/MybatisInterceptor.java");



        //1、生成api层代码------------java代码
        String api_dir  = app_name+"-"+module_name+"-api";
        deal(context,zip,null, "template/proj/api/pom.xml.vm",proj_dir+"."+api_dir + ".pom.xml");
        deal(context,zip,null, "template/proj/api/application.properties.vm",proj_dir + "."+api_dir+".src.main.resources.application.properties");
        deal(context,zip,null, "template/proj/api/application-dev.properties.vm",proj_dir + "."+api_dir+".src.main.resources.application-dev.properties");
        deal(context,zip,null, "template/proj/api/common/config/SwaggerConfig.java.vm",proj_dir + "."+api_dir+".src.main.java."+app_pck_name + "/"+module_name+"/api/common/config/SwaggerConfig.java");
        deal(context,zip,null, "template/proj/api/controller/BaseController.java.vm",proj_dir + "."+api_dir+".src.main.java."+app_pck_name + "/"+module_name+"/api/controller/BaseController.java");
        deal(context,zip,null, "template/proj/api/ApiApplication.java.vm",proj_dir + "."+api_dir+".src.main.java."+app_pck_name + "/"+module_name+"/api/"+StringUtils.capitalize(module_name)+"ApiApplication.java");//todo

    }

}
